package com.etooling.pdm.repository;

import com.etooling.framework.repository.BaseRepository;
import com.etooling.pdm.entity.Bom;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Repository
public interface BomRepository extends BaseRepository<Bom> {


    @Query(nativeQuery = true, value = "select * from pdm.t_bom where goods_specs_id =?1 and status = ?2")
    List<Bom> getStatusBom(String specsId, String statusRun);

    @Query(nativeQuery = true, value = "select * from pdm.t_bom where goods_specs_id =?1 ")
    List<Bom> getBom(String specsId);

    @Query(nativeQuery = true, value = "select id, audit_time, audit_user_id, audit_user_name, bom_name, company_id, create_time, create_user_id, create_user_name, memo, status, version_code, goods_specs_id, batch_id from pdm.t_bom where id = ?1 ")
    Map<String, Object> getBomInfo(String bomId);

    @Query(nativeQuery = true, value = "select id, audit_time, audit_user_id, audit_user_name, bom_name, company_id, create_time, create_user_id, create_user_name, memo, status, version_code, goods_specs_id, batch_id from pdm.t_bom where goods_specs_id = ?1 ")
    List<Map<String, Object>> getBomInfoOptions(String specsId);

    @Query(nativeQuery = true, value = "select * from pdm.t_bom where goods_specs_id = ?1 ")
    List<Bom> findByGoodsSpecsId(String specsId);

    @Query(nativeQuery = true, value = "select id, audit_time, audit_user_id, audit_user_name, bom_name, company_id, create_time, create_user_id, create_user_name, memo, status, version_code, goods_specs_id, batch_id from pdm.t_bom where goods_specs_id=?1 ")
    List<Map<String, Object>> getBomHistory(String specsId);


    /**
     * 启用Bom
     *
     * @param bomId         bom的id
     * @param goodsSpecsId  bom所属的产品id
     * @param enableStatus  启用状态
     * @param disableStatus 禁用状态
     */
    @Transactional
    @Modifying
    @Query(nativeQuery = true, value = "" +
            "UPDATE pdm.t_bom " +
            "SET status = CASE WHEN id = ?1 THEN ?3  ELSE ?4 END " +
            "WHERE goods_specs_id = ?2")
    void updateEnableBom(String bomId, String goodsSpecsId, String enableStatus, String disableStatus);


}
